<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类目" prop="category">
        <el-input
          v-model="queryParams.category"
          placeholder="请输入商品类目"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品属性" prop="productAttribute">
        <el-input
          v-model="queryParams.productAttribute"
          placeholder="请输入商品属性"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeleteAll"
          v-hasPermi="['system:products:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="showImportDialog"-->
<!--          v-hasPermi="['system:products:import']"-->
<!--        >导入</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:products:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表格区域 -->
    <el-table v-loading="loading" :data="productsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" align="center" prop="productId" />
      <el-table-column label="商品图片" align="center" prop="productImage" >
        <template slot-scope="scope">
          <el-image :src="scope.row.productImage" fit="fill" :preview-src-list="[scope.row.productImage]" />
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="商品类目" align="center" prop="category" />
      <el-table-column label="商品类型" align="center" prop="productType" />
      <el-table-column label="售价" align="center" prop="price" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="商品属性" align="center" prop="productAttribute" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <pagination
      @size-change="handleSizeChange"
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      :page-sizes="[3, 6, 10, 15,20]"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品类目" prop="category">
          <el-input v-model="form.category" placeholder="请输入商品类目" />
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-input v-model="form.price" placeholder="请输入售价" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="商品属性" prop="productAttribute">
          <el-input v-model="form.productAttribute" placeholder="请输入商品属性" />
        </el-form-item>
        <el-form-item label="商品详情描述" prop="productDetail">
          <el-input v-model="form.productDetail" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 商品详情对话框 -->
    <el-dialog :title="'商品详情'" :visible.sync="detailVisible" width="600px" append-to-body>
      <el-form ref="detailForm" :model="detailForm" label-width="100px">
        <el-form-item label="商品名称">
          <el-input v-model="detailForm.productName" disabled />
        </el-form-item>
        <el-form-item label="商品类目">
          <el-input v-model="detailForm.category" disabled />
        </el-form-item>
        <el-form-item label="商品详情">
          <el-input v-model="detailForm.productDetail" type="textarea" :rows="10" disabled style="width: 100%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!--导入弹窗区域-->
    <el-dialog title="导入商品信息" :visible.sync="importDialog" width="450px">
      <div class="import-tip">
        <p>1. 请确保Excel文件格式正确，避免导入失败</p>
        <p>2. 单次导入最多支持100条商品信息</p>
        <p>3. 支持的文件格式：.xlsx, .xls</p>
        <p>4. <el-button type="text" size="small" @click="downloadTemplate">下载导入模板</el-button></p>
      </div>
      <!--上传组件-->
      <el-upload
        class="upload-demo"
        drag
        :auto-upload="false"
        :file-list="fileList"
        :before-upload="beforeUpload"
        :on-change="handleChange"
        :limit="1"
        :on-exceed="handleExceed"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传Excel文件，且不超过5MB
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelImport">取 消</el-button>
        <el-button type="primary" @click="confirmImport" :loading="uploadLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listProducts, getProducts, addProducts, delProducts, updateProducts, uploadExcel, exportProducts} from "@/api/product/listProducts"

export default {
  name: "ProductList",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 上传加载状态
      uploadLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      productsList: [],
      // 弹出层标题
      title: "",
      // 商品详情对话框标题
      detailTitle: "",
      // 商品详情对话框是否可见
      detailVisible: false,
      // 商品详情表单参数
      detailForm: {},
      // 是否显示弹出层
      open: false,
      // 是否显示导入弹窗
      importDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        category: null,
        productType: null,
        productAttribute: null,
        status: null,
        productDetail: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
      },
      file: null,
      fileList: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询商品信息列表 */
    getList() {
      this.loading = true
      listProducts(this.queryParams).then(response => {
        console.log("response", response)
        this.productsList = response.rows || []
        this.total = Number(response.total) || 0  // 确保total为数字类型
        this.loading = false
      }).catch(() => {
        this.total = 0  // 错误处理时重置为0
        this.loading = false
      })
    },
    /** 每页条数改变 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        productName: null,
        category: null,
        productType: null,
        price: null,
        unit: null,
        productAttribute: null,
        status: null,
        productDetail: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加商品信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const productId = row.productId || this.ids
      this.form = row
      console.log("form" , this.form)
      this.open = true
      this.title = "修改商品信息"
    },
    // 详情按钮操作
    handleDetail(row) {
      this.loading = true;
      // 调用API查询完整商品信息（包含productDetail）
      getProducts(row.productId).then(response => {
        this.detailForm = response.data;
        this.detailVisible = true;
      }).catch(() => {
        this.$modal.msgError("获取商品详情失败");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productId != null) {
            updateProducts(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addProducts(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids
      this.$modal.confirm('是否确认删除商品信息编号为"' + productIds + '"的数据项？').then(function() {
        return delProducts(productIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },

    // 删除所有选中商品
    handleDeleteAll() {
      this.$modal.confirm('是否确认删除选中的商品信息？').then(() => {
        this.ids.forEach(id => {
          delProducts(id)
        })
        this.ids = []
        this.getList()
        this.$modal.msgSuccess("删除成功")
      })
    },
    // 上传前的回调，用于清空上次上传的文件列表
    beforeUpload(file) {
      console.log('开始上传，清空上次的文件列表');
      this.fileList = []; // 清空文件列表
      // 校验文件类型
      const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
      if (!isExcel) {
        this.$message.error('只能上传Excel文件！');
        return false;
      }
      // 校验文件大小（5MB）
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过5MB！');
        return false;
      }
      return true;
    },
    // 显示导入弹窗
    showImportDialog() {
      this.importDialog = true;
      this.fileList = [];
      this.file = null;
    },
    // 导出商品数据
    exportProductsData() {
      this.$confirm('确定要导出当前商品数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 创建临时查询参数，不包含分页信息
        const exportParams = { ...this.queryParams };
        // 移除分页参数，导出全部数据
        delete exportParams.pageNum;
        delete exportParams.pageSize;

        this.loading = true;
        exportProducts(exportParams).then(response => {
          // 处理文件下载
          const blob = new Blob([response]);
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;

          // 设置文件名
          const fileName = `商品数据_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`;
          link.download = fileName;

          // 模拟点击下载
          document.body.appendChild(link);
          link.click();

          // 清理
          window.URL.revokeObjectURL(url);
          document.body.removeChild(link);

          this.$message.success('导出成功！');
        }).catch(error => {
          console.error('导出失败:', error);
          this.$message.error('导出失败，请联系管理员！');
        }).finally(() => {
          this.loading = false;
        });
      }).catch(() => {
        // 用户取消导出
      });
    },
    // 取消导入
    cancelImport() {
      this.importDialog = false;
      this.fileList = [];
      this.file = null;
    },
    // 确认导入
    confirmImport() {
      if (!this.file) {
        this.$message.warning('请先选择要上传的文件！');
        return;
      }
      this.uploadExcelFun();
    },
    // 上传文件
    uploadExcelFun() {
      const file = this.file;
      if (!file) {
        this.$message.warning('请先选择文件！');
        return;
      }

      // FormData是js对象,用于存储表单数据
      const formData = new FormData();
      formData.append("file", file); // 由后端接口决定,后端参数叫file

      this.uploadLoading = true;
      // 封装的上传文件方法
      uploadExcel(formData).then((res) => {
        if (res.code === 200) {
          this.$message({
            message: res.msg || "商品信息导入成功",
            type: "success",
          });
          // 上传成功后添加到文件列表
          this.fileList.push({
            name: file.name,
          });
          this.cancelImport(); // 关闭弹窗并清空
          this.queryParams.pageNum = 1; // 刷新列表
          this.getList(); // 刷新商品列表
        } else {
          this.$message.error(res.msg || '导入失败！');
        }
      }).catch((error) => {
        console.error('导入失败:', error);
        this.$message.error('导入失败，请检查文件格式或联系管理员！');
      }).finally(() => {
        this.uploadLoading = false;
      });
    },
    // 下载导入模板
    downloadTemplate() {
      // 这里应该调用后端提供的下载模板接口
      // 假设后端接口为 /product/downloadTemplate
      window.open(`/dev-api/product/downloadTemplate`, '_blank');
      this.$message.success('正在下载模板文件...');
    },
    // 监听文件改变
    handleChange(file) {
      console.log("file",file)
      this.file = file.raw;
    },
    // 处理文件超出个数限制
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制只能上传1个文件，您选择了 ${files.length} 个文件`);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/product/export', {
        ...this.queryParams
      }, `products_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.import-tip {
  background-color: #f0f9ff;
  border: 1px solid #d6ecff;
  border-radius: 4px;
  padding: 10px 15px;
  margin-bottom: 15px;
}
.import-tip p {
  margin: 5px 0;
  font-size: 12px;
  color: #409eff;
}
</style>
